package servlet;

import entity.Emp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 石小俊
 */
@WebServlet("/findById")
public class ShowModifyEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        Emp emp = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                // 将查询到的员工信息保存到request作用域中
                request.setAttribute("emp",emp);
                // 转发
                request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
                // 此处业务结束,必须使用return
                return;
            }
            request.setAttribute("empMsg","未找到对应员工");
            request.getRequestDispatcher("/findAll").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/findAll").forward(request,response);
        }
    }

}
